package cliente;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.StringTokenizer;

public class Cliente implements Runnable {

    private Socket server;
    private PrintStream ps;
    private BufferedReader is;
    private String nick = "";

    public int connect(String ip, int port) {
        return connectTo(ip, port);
    }

    public int connect(String ip) {
        return connectTo(ip, 7000);
    }

    public int connect() {
        return connectTo("127.0.0.1", 7000);
    }
    
    public void createChannel(String name) {
        ps.println("CREATECHANNEL:{name=\"#" + name + "\"}");
    }
    public void joinChannel(String name) {
        ps.println("JOINCHANNEL:{name=\"#" + name + "\"}");
    }
    private int connectTo(String ip, int port) {
        try {
            //Cria o socket com o recurso desejado na porta especificada  
            this.server = new Socket(ip, port);

            //Cria a Stream de saida de dados  
            this.ps = new PrintStream(server.getOutputStream());


            //SERVERCONNECT PROTOCOL
            //"SERVERCONNECT:{nick="%NICK%"}
            ps.println("SERVERCONNECT:{nick=\"" + (nick.isEmpty() ? "" : nick) + "\"}");


            //Cria a Stream de entrada de dados
            this.is = new BufferedReader(new InputStreamReader(server.getInputStream()));
            String retorno = is.readLine();
            if (retorno.contains("SERVERCONNECT")) {
                if (retorno.contains("status=\"Accept\"")) {
                    System.out.println("OK");
                    return 0;
                } else if (retorno.contains("status=\"Refuse\"")) {
                    System.out.println("SHIT");
                    return 1;
                }
            } else {
                System.out.println(retorno);
            }

        } catch (IOException e) {  //Trata possíveis exceções

            System.out.println("Erro aqui.");
        }

        return -1;
    }

    public void setNick(String nick) {
        this.nick = nick;
    }

    public void sendMessage(String message, String destination) {
        ps.println("MESSAGE:{msg=\"" + message + "\",toUser=\"" + destination + "\"}");
        //TODO
    }

    @Override
    public void run() {
        try {
            String retorno;
            while ((retorno = is.readLine()) != null) {
                System.out.println(retorno);
            }
        } catch (IOException e) {
        }
    }
}